package com.cxmx.escort.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cxmx.escort.base.*;
import com.cxmx.escort.common.SnowflakeIdWorker;
import com.cxmx.escort.entity.BedOrder;
import com.cxmx.escort.entity.User;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 充值表 前端控制器
 * </p>
 *
 * @author 陈云轩
 * @since 2019-10-21
 */
@RestController
@RequestMapping("/bedOrder")
@Validated
@Api(value = "床订单", tags = {"陪护床订单操作接口"})
@SuppressWarnings("unchecked")
public class BedOrderController extends BaseController {
    @ApiOperation(value = "正在进行的订单", httpMethod = "GET")
    @GetMapping("for")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", dataType = "String", paramType = "header", required = true),
    })
    public Result<BedOrder> getPageForOne(
            @NotNull(message = "token不可为空") @RequestHeader("token") String token

    ) {
        QueryWrapper<BedOrder> qw = new QueryWrapper<BedOrder>();
        qw.eq("user_id", getLongTypeUserId(token));
        qw.ne("order_status", 3);
        BedOrder bedOrder = bedOrderService.getOne(qw);
        if (null != bedOrder && bedOrder.getOrderStatus() == 1) {
            bedOrder.setPrice(new BigDecimal(MD5Utils.getPrice(bedOrder.getLockTime(), LocalDateTime.now(), bedOrder.getUnitCost().doubleValue(), getStringTypeUserId(token))));
            bedOrderService.updateById(bedOrder);
        }
        return ResponseFormat.retParam(200, bedOrder);
    }

    @ApiOperation(value = "页面加载时正在进行订单", httpMethod = "GET")
    @GetMapping("ing")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", dataType = "String", paramType = "header", required = true),
    })
    public Result<BedOrder> getOrder(
            @NotNull(message = "token不可为空") @RequestHeader("token") String token

    ) {
        QueryWrapper<BedOrder> qw = new QueryWrapper<BedOrder>();
        qw.eq("user_id", getLongTypeUserId(token));
        qw.eq("read_flag", 1);
        qw.ne("order_status", 1);
        qw.orderByDesc("update_time");
        List<BedOrder> bedOrder = bedOrderService.list(qw);
        if (null != bedOrder && bedOrder.size() > 0) {
            BedOrder returnBedOrder = bedOrder.get(0);
            if (returnBedOrder.getOrderStatus() != 1) {
                returnBedOrder.setReadFlag(2);
                bedOrderService.updateById(returnBedOrder);
            }
            return ResponseFormat.retParam(200, bedOrder.get(0));
        }
        return ResponseFormat.retParam(200, null);
    }

    @ApiOperation(value = "消费列表", httpMethod = "GET")
    @GetMapping("/{pageNum}/{pageSize}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", dataType = "String", paramType = "header", required = true),
            @ApiImplicitParam(paramType = "path", dataType = "String", name = "pageNum", value = "分页", required = true),
            @ApiImplicitParam(paramType = "path", dataType = "int", name = "pageSize", value = "每一页条数", required = true),
    })
    public Result<BasePage<BedOrder>> getPageForOne(@NotNull(message = "pageNum不能为空") @Min(value = 1, message = "分页最小为1") @PathVariable("pageNum") Integer pageNum,
                                                    @NotNull(message = "pageSize不能为空") @Max(value = 20, message = "每页最大20") @PathVariable("pageSize") Integer pageSize,
                                                    @NotNull(message = "token不可为空") @RequestHeader("token") String token

    ) {
        QueryWrapper<BedOrder> qw = new QueryWrapper<BedOrder>();
        qw.eq("user_id", getLongTypeUserId(token));
        qw.eq("order_status", 3);
        qw.orderByDesc("create_time");
        Page<BedOrder> page = new Page<>(pageNum, pageSize);
        IPage<BedOrder> roleDOList = bedOrderService.page(page, qw);
        return ResponseFormat.retParam(200, roleDOList);
    }

    @ApiOperation(value = "付款订单", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", dataType = "String", paramType = "header", required = true),
    })
    @PostMapping
    public Result<Boolean> addTop(String orderIId, @NotNull(message = "token不可为空") @RequestHeader("token") String token) throws WxPayException {
        User user = userService.getById(getLongTypeUserId(token));
        BedOrder bedOrder = bedOrderService.getById(orderIId);
        WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest = new WxPayUnifiedOrderRequest();
        Double price = bedOrder.getUnpaidPrice().doubleValue() * 100;
        wxPayUnifiedOrderRequest.setTotalFee(Integer.parseInt(String.valueOf(price.intValue())));
//        wxPayUnifiedOrderRequest.setTotalFee(1);
        wxPayUnifiedOrderRequest.setBody("陪护床超出费用缴费");
        String id = String.valueOf(SnowflakeIdWorker.getId());
        wxPayUnifiedOrderRequest.setOutTradeNo(orderIId);
        wxPayUnifiedOrderRequest.setOpenid(user.getOpenId());
        wxPayUnifiedOrderRequest.setTradeType("JSAPI");
        wxPayUnifiedOrderRequest.setSpbillCreateIp("47.105.133.34");
        wxPayUnifiedOrderRequest.setNotifyUrl("https://api.bochenkj.cn/pay/notify/bedOrder");
        wxPayUnifiedOrderRequest.setFeeType("CNY");
        wxPayUnifiedOrderRequest.setVersion("1.0");
        return ResponseFormat.retParam(200, wxService.createOrder(wxPayUnifiedOrderRequest));
    }
}

